package top.tenebrous.yzl.utils;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author hrz
 */
public class MapUrlParamsUtils {
    /**
     * 将url参数转换成map
     *
     * @param param aa=11&bb=22&cc=33
     * @return
     */
    public static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        if (StringUtils.isBlank(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (String s : params) {
            String[] p = s.split("=", 2);
            if (p.length == 2) {
                try {
                    map.put(URLDecoder.decode(p[0], "UTF-8"), URLDecoder.decode(p[1], "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    /**
     * 将map转换成url
     *
     * @param map
     * @return
     */
    public static String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof List) {
                List collection = (List) value;
                for (int i = 0; i < collection.size(); i++) {
//                    if (JSON.isValidObject(collection.get(i).toString())) {
//                        JSONObject obj = JSON.parseObject(collection.get(i).toString());
//                        List<Map.Entry<String, Object>> list = new LinkedList<>(obj.entrySet());
//                        list.sort(Map.Entry.comparingByKey());
//                        for (Map.Entry entry1 : list) {
//                            sb.append(entry.getKey()).append("[" + i + "]").append("[" + entry1.getKey() + "]").append("=").append(entry1.getValue());
//                            sb.append("&");
//                        }
//                    } else {
//                        sb.append(entry.getKey()).append("[" + i + "]").append("=").append(collection.get(i).toString());
//                        sb.append("&");
//                    }
                }
            } else {
                sb.append(entry.getKey()).append("=").append(entry.getValue());
                sb.append("&");
            }
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    public static LinkedHashMap<String, Object> sortByKey(Map<String, Object> map) {
        List<Map.Entry<String, Object>> list = new LinkedList<>(map.entrySet());

        list.sort(Map.Entry.comparingByKey());

        LinkedHashMap<String, Object> result = new LinkedHashMap<>();
        for (Map.Entry<String, Object> entry : list) {
            if (entry.getValue() != null)
                result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    private final static String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIzmjwZn2vN5aYVsTh0dU04LfiBOj94GKoBOUe+7bAHbkmmPyrFeRQhB4Iruu9pBTT2d+JriVZRxWWRsJ30/xfmaMdoT8HPObCGzs+kYaGH6nYyvR0gQOYiqWkC9/F6UAQO57iKtOkMXy0kFHqhcZPly02t/GM5dLFfBIZt9YxRrAgMBAAECgYBGvMF1T9KGhZ/KUjNtPnnCJtbtVUO5DZNs0uUj3A4/aIK66Gu0XEV//cLDPVOmIT6r/pD/AT5Bxh5A4mN45/l1syXuIt4EvQ40OWYq09HqAFYbfDmEhQ0SZiOBao0wZqUhFZ6HkmM2g8rm8zX35kHx8UsJIwJwHJrrDgq98WeFIQJBAN7XlCpkf6plLVm3gYn67cpmRRdQt95sgVKXvP+5ZrBZHYNedNErPxwpZAW4b39ONk9fitQNxKYFMP+7rldcWKMCQQCh3bHDC/LvJG7udDGy1ds/0rk4WKgDuhRHy2tPuXnr3D/zHw1iOP47pA1BB62eaLD3/2m7drLEF4vFuc1fACmZAkA1wgfqWig6MQJJvG0xnikzRIyyXTSeIcro49YiUtWlATqPcH/53dbxskKA5sdvDK0pZMEW+uNPsbzqVJpwVMTFAkAD8mHpPZtY1WyXB+JGWAyWi87UXuUJ4jmoXn9pXD5qz94HUZSD9pvMXH2uPj+vgyH9ig7L8WL+gQx5b8RgMqLRAkEA2oxg7us4D1eLw8IoM/F1l3YApfffWKm4c78moKYEZDhDJOT0cAQoeCugAnoJ4BsiXjzn6iZo9BAvNCGzxQq9TA==";


    public static void main(String[] args) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("aa", "ceshi");
        params.put("bb", "ceshi");
        params.put("dd", "ceshi");
        params.put("d1d", "ceshi");
        params.put("bb1", "ceshi");
        params.put("a1", "ceshi");

        LinkedHashMap<String, Object> sortedParam = MapUrlParamsUtils.sortByKey(params);
        String verifyStr = MapUrlParamsUtils.getUrlParamsByMap(sortedParam);
        RSA rsa = new RSA(PRIVATE_KEY, null);
        byte[] encryptByte = rsa.encrypt(verifyStr.getBytes(), KeyType.PrivateKey);
        String encryptStr = org.apache.commons.codec.binary.Base64.encodeBase64String(encryptByte);
        System.out.println("encryptStr:" + encryptStr);
        //最终sign放入参数到里
        params.put("sign", encryptByte);


        //---公钥解密-----------------
        byte[] decodeByte = Base64.decodeBase64(encryptStr);
        byte[] decryptByte = rsa.decrypt(decodeByte, KeyType.PublicKey);
        String decryptStr = new String(decryptByte);
        System.out.println("decryptStr:" + decryptStr);
        System.out.println("---------------------------");
    }
}
